/************************************************************************
                                                                     
   Xceed Ultimate ListBox for Silverlight                                                                                                                                            
   Copyright (C) 2010 Xceed Software Inc.    
                                                                     
   This program is provided to you under the terms of the GNU General Public  
   License version 2 as published by the Free Software Foundation. 
        
   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY, without even the implied warranty of 
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License along 
   with this program, if not, write to the Free Software Foundation, Inc., 
   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

   This program can be provided to you by Xceed Software Inc. under a
   proprietary commercial license agreement for use in non-Open Source
   projects. Visit Xceed.com to find the commercial edition of 
   Xceed Ultimate ListBox for Silverlight.                                    
                                                                      
 **********************************************************************/

using System;
using Xceed.Silverlight.Data.Stats;
using System.Collections.Generic;
using System.Linq;

namespace Xceed.Silverlight.Data
{
  internal class GroupContextEnumerator : AsyncParentEnumerator<DataPath>
  {
    private static readonly Guid JumpMoveAndFetchCallId = DataUtils.CreateCallId();

    public GroupContextEnumerator( IGroupEnumerator childEnumerator )
      : base( childEnumerator )
    {
    }

    private IGroupEnumerator GroupEnumerator
    {
      get
      {
        return ( IGroupEnumerator )this.ChildEnumerator;
      }
    }

    public GroupHelper GroupHelper
    {
      get
      {
        return this.GroupEnumerator.GroupHelper;
      }
    }

    private JumpMoveAndFetchAsyncResult BaseBeginJumpMoveAndFetch( JumpMoveAndFetchParameters parameters, AsyncCallback userCallback, object asyncState )
    {
      return base.BeginJumpMoveAndFetch( parameters, userCallback, asyncState );
    }

    private JumpMoveAndFetchResult<DataPath> BaseEndJumpMoveAndFetch( JumpMoveAndFetchAsyncResult jumpMoveAndFetchAsyncResult )
    {
      return base.EndJumpMoveAndFetch( jumpMoveAndFetchAsyncResult );
    }


    public override JumpMoveAndFetchAsyncResult BeginJumpMoveAndFetch( JumpMoveAndFetchParameters parameters, AsyncCallback userCallback, object asyncState )
    {
      JumpMoveAndFetchAsyncResult asyncResult = new JumpMoveAndFetchAsyncResult( GroupContextEnumerator.JumpMoveAndFetchCallId, userCallback, asyncState, parameters );

      asyncResult.Start(
        ( callback, state ) => this.BaseBeginJumpMoveAndFetch( parameters, callback, state ),
        ( parentAr, childAr ) => this.HandleGroupContexts( this.BaseEndJumpMoveAndFetch( ( JumpMoveAndFetchAsyncResult )childAr ) ) 
        );

      return asyncResult;
    }

    public override JumpMoveAndFetchResult<DataPath> EndJumpMoveAndFetch( JumpMoveAndFetchAsyncResult jumpMoveAndFetchAsyncResult )
    {
      jumpMoveAndFetchAsyncResult.ValidateCallEnd( GroupContextEnumerator.JumpMoveAndFetchCallId );
      return jumpMoveAndFetchAsyncResult.GetCallResult<JumpMoveAndFetchResult<DataPath>>();
    }

    private DependentCallResult HandleGroupContexts( JumpMoveAndFetchResult<DataPath> result )
    {
      if( result.FetchedItems == null )
        return new DependentCallResult( result );

      IEnumerator<DataPath> goupItemEnumerator = result.FetchedItems.GetEnumerator();

      if( !goupItemEnumerator.MoveNext() )
        return new DependentCallResult( result );

      return this.HandleGroupContextsCallback( result, goupItemEnumerator, 0 );
    }

    private DependentCallResult HandleGroupContextsCallback(
      JumpMoveAndFetchResult<DataPath> result,
      IEnumerator<DataPath> fetchedItems,
      int currentDepth )
    {
      IGroupStatFunctionsSelector statFunctionsSelector = this.GroupHelper.GroupHandler.GroupStatFunctionsSelector;
      bool includeCount = this.GroupHelper.GroupHandler.IncludeGroupItemsCount;
      bool includeItems = this.GroupHelper.GroupHandler.IncludeGroupItems;

      // There is nothing to do if there is no selector.
      if( statFunctionsSelector == null && !includeCount && !includeItems )
        return new DependentCallResult( result );

      DataPath groupPath;
      IEnumerable<StatFunction> statFunctions = null;

      do
      {
        // There is no more group to verify.
        if( !this.MoveToNextGroup( ref fetchedItems, ref currentDepth ) )
          return new DependentCallResult( result );

        groupPath = fetchedItems.Current.CreateAncestorOrSamePath( currentDepth );

        // Retrieve the active stat functions for the group.
        if( statFunctionsSelector != null )
        {
          statFunctions = statFunctionsSelector.GetStatFunctions( groupPath );
        }
      } while( !includeCount && !includeItems && ( statFunctions == null || !statFunctions.Any() ) );

      GroupDataItem dataItem = ( GroupDataItem )groupPath.LastChild;
      List<DependentCallResult> contextCallsList = new List<DependentCallResult>();
      IEnumerator<DependentCallResult> contextCalls = null;

      Func<AsyncCallback, object, IAsyncResult> includeItemsCall = null;
      Func<AsyncResult, IAsyncResult, DependentCallResult> includeItemsCallback = null;

      if( includeCount || includeItems )
      {
        contextCallsList.Add(
        new DependentCallResult( null,
        ( callback, state ) => this.GroupEnumerator.BeginGroupItemCount( groupPath, callback, state ),
        ( parentAr, childAr ) =>
        {
          dataItem.ItemCount = this.GroupEnumerator.EndGroupItemCount( childAr );

          if( includeItems && dataItem.ItemCount != null && !dataItem.ItemCount.IsEstimate )
          {
            return new DependentCallResult( null, includeItemsCall, includeItemsCallback );
          }
          else
          {
            contextCalls.MoveNext();
            return contextCalls.Current;
          }
        } ) );
      }

      // A precise item count is required
      includeItemsCall = ( callback, state ) =>
      {
        int itemCount = Convert.ToInt32( dataItem.ItemCount.Value );
        SortPosition startPosition = this.GroupHelper.CreateSortPositionForGroup( groupPath, StartPosition.Before );
        JumpMoveAndFetchParameters parameters = new JumpMoveAndFetchParameters( startPosition, 0, itemCount, false );
        return this.GroupEnumerator.BeginGetBaseItems( parameters, callback, state );
      };

      includeItemsCallback = ( parentAr, childAr ) =>
      {
        dataItem.Items = this.GroupEnumerator.EndGetBaseItems( ( JumpMoveAndFetchAsyncResult )childAr ).FetchedItems;

        contextCalls.MoveNext();
        return contextCalls.Current;
      };

      if( statFunctions != null )
      {
        StatParameters parameters = new StatParameters( statFunctions, groupPath );

        contextCallsList.Add(
        new DependentCallResult( null,
        ( callback, state ) => this.BeginGetStatValues( parameters, callback, state ),
        ( parentAr, childAr ) =>
        {
          StatResults results = this.EndGetStatValues( childAr );

          dataItem.StatContext = new StatContext(
                                   parameters.StatFunctions.Select( ( func ) => func.ResultPropertyName ),
                                   results.Results );

          contextCalls.MoveNext();
          return contextCalls.Current;
        } ) );
      }

      //Final Call
      contextCallsList.Add(
      new DependentCallResult( null,
        ( callback, state ) =>
        {
          AsyncResult endResult = new AsyncResult( Guid.Empty, callback, state );
          endResult.StartSync( null );
          return endResult;
        },
        ( parentAr, childAr ) =>
        {
          return this.HandleGroupContextsCallback( result, fetchedItems, currentDepth );
        } ) );

      contextCalls = contextCallsList.GetEnumerator();
      contextCalls.MoveNext();
      return contextCalls.Current;
    }

    private bool MoveToNextGroup(
      ref IEnumerator<DataPath> fetchedItems,
      ref int currentDepth )
    {
      currentDepth++;
      DataPath currentPath = fetchedItems.Current;

      while( currentDepth > currentPath.Depth
        || !( currentPath[ currentDepth - 1 ] is GroupDataItem ) )
      {
        if( !fetchedItems.MoveNext() )
          return false;

        currentPath = fetchedItems.Current;
        currentDepth = 1;
      }

      return true;
    }
  }

}
